import {Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core';
import {SelectorGen, SelectorItem} from './interface';
import {DropdownDataService, Option as DropdownOption} from '@dropdown';

@Component({
    selector: 'kylin-list-page-selector',
    templateUrl: './selector.component.html',
    styleUrls: [
        './selector.component.less'
    ]
})
export class SelectorComponent implements OnInit, OnChanges {
    @Input() isCollapse: boolean;
    @Input() splitScale: number;
    _selectorGen: SelectorGen;
    @Input() set selectorGen(val: SelectorGen) {
        this._selectorGen = val;
        this._selectorGen.btnPosition = (val && val.btnPosition) || 'default';
        this.splitScale = val.splitScale || 3;
        this.isCollapse = val.isCollapse || false; // 默认展开
        this.classCover = val.classCover;
    };

    @Output() query = new EventEmitter<any>();
    splitSelector: Array<Array<SelectorItem>>;
    classCover: string;

    constructor(private dropdownDataSvc: DropdownDataService) {
    }

    ngOnChanges(changes) {
        if (changes.selectorGen) {
            this.splitSelectorByNum();
            this.genSelectedBind();
        }
    }

    ngOnInit() {
    }

    genSelectedBind() {
        const dropdownArr = new Array<any>();
        this._selectorGen.selectorArr.map((item, index) => {
            const {key, dataSource, type, selectedIdx} = item;
            let value: any = null;
            switch (type) {
                // 初值处理
                case('dropdown') :
                    if (typeof dataSource === 'string' || !dataSource) {
                        dropdownArr.push(item);
                    } else {
                        value = dataSource[selectedIdx] ? dataSource[selectedIdx].value : null;
                    }
                    break;
                case ('numberRange'):
                    value = {
                        start: '',
                        end: ''
                    };
                    break;
                case('cascader'):
                    if (typeof dataSource === 'string' || !dataSource) {
                        dropdownArr.push(item);
                    } else {
                        value = [];
                    }
                    break;
                case('customerCascader'):
                case('customerCascaderMultiple'):
                    value = item.cascaderOptions ? item.cascaderOptions.map(option => option.selectedValue || '') : []
                    break;
                case('dateRange'):
                case('timeRange'):
                case('projects'):
                    value = [];
                    break;
                default:
                    item.type = item.type || 'text';
                    break;
            }
            item.value = value;
        });
        // 针对没有dataSource或 dataSource为 string 的下拉选，获取下拉列表数据
        this.getDropDownData(dropdownArr).then(rst => {
            Object.keys(rst).map(key => {
                const selectItem = this._selectorGen.selectorArr.find(item => item.key === key);
                selectItem.dataSource = rst[key];
                selectItem.value = selectItem.selectedIdx ? (selectItem.dataSource[selectItem.selectedIdx] as any).value : null;
            });
            this.execQuery();
        });
    }

    splitSelectorByNum() {
        const num = this.splitScale;
        const splitSelector = new Array<any>();
        for (let i = 0; i < this._selectorGen.selectorArr.length; i++) {
            if (i % num === 0) {
                splitSelector.push(this._selectorGen.selectorArr.slice(i, i + num));
            }
        }
        this.splitSelector = splitSelector;
    }

    processBindMap = () => {
        const processedData = {};

        this._selectorGen.selectorArr.map(item => {
            const {type, value, cascaderProps, key} = item;
            switch (type) {
                case 'date':
                case 'time':
                    processedData[key] = value ? value.getTime() + '' : '';
                    break;
                case 'dateRange':
                case 'timeRange':
                    processedData[item.startProp || key + 'StartTime'] = value[0] ? this.dateRangeHandler(value[0], 'start') + '' : '';
                    processedData[item.endProp || key + 'EndTime'] = value[1] ? this.dateRangeHandler(value[1], 'end') + '' : '';
                    break;
                case('numberRange'):
                    processedData[item.startProp || key + 'Start'] = value['end'] ? value['start'] || 0 : value['start'];
                    processedData[item.startProp || key + 'End'] = value['start'] ? value['end'] || Number.MAX_SAFE_INTEGER : value['end'];
                    break;
                case 'cascader':
                case 'customerCascader':
                case('customerCascaderMultiple'):
                    if (Array.isArray(cascaderProps)) {
                        cascaderProps.map((prop, idx) => {
                            let fromProp;
                            let toProp;
                            if (prop) {
                                if (typeof prop === 'string') {
                                    processedData[prop] = value ? value[idx] || '' : '';
                                } else {
                                    fromProp = prop.from || '';
                                    toProp = prop.to || '';
                                    processedData[toProp] = value ? value[idx][fromProp] || '' : '';
                                }
                            }
                        });
                    } else {
                        processedData[key] = value ? JSON.stringify(value) : '';
                    }
                    break;
                case('projects'):
                    processedData[key] = value && value.length ? value.join(',') : '';
                    break;
                case 'text':
                case 'dropdown':
                default:
                    processedData[key] = value || '';
            }
        });
        return processedData;
    }

    getSelectedMap = () => {
        let params;
        params = this.processBindMap();
        if (this._selectorGen.dataProcess) {
            params = this._selectorGen.dataProcess(params);
        }
        return params;
    }


    /** 生成下拉列表的数据 **/
    getDropDownData(selectItem: SelectorItem[]) {
        const options = selectItem.map(item => {
            if (item.dataSource instanceof DropdownOption) {
                return item.dataSource;
            } else {
                return {
                    name: typeof item.dataSource === 'string' ? item.dataSource : item.key,
                    params: item.dataSourceParams,
                    cache: true,
                    labelFrom: item.labelFrom,
                    valueFrom: item.valueFrom,
                    targetKey: item.key
                };
            }
        });
        return this.dropdownDataSvc.getDataByGroup(options);
    }

    execQuery() {
        this.query.emit(this.getSelectedMap());
    }

    renderOptions(param) {
        // TODO 卡顿处理，代码完善
        // selectorItem.hexOpen = true;
    }

    toggleCollapse() {
        this.isCollapse = !this.isCollapse;
    }

    setSelector() {

    };

    isArray(obj) {
        return Array.isArray(obj);
    }


    private dateRangeHandler(date: Date, type: 'start' | 'end'): number {
        const year = date.getFullYear();
        const month = date.getMonth();
        const day = date.getDate();
        if (type === 'start') {
            return new Date(year, month, day, 0, 0, 0).getTime();
        } else {
            return new Date(year, month, day, 23, 59, 59).getTime();
        }
    }
}
